package com.yin.waimai.service.impl;

import com.yin.waimai.model.User;
import com.yin.waimai.repository.UserRepository;
import com.yin.waimai.service.AppUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service // 将这个类标记为 Spring 服务组件
public class UserDetailsServiceImpl implements AppUserDetailsService {

    private final UserRepository userRepository;

    @Autowired
    public UserDetailsServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中根据用户名查找用户
        User user = userRepository.findByUsername(username)
                .orElseThrow(() ->
                        new UsernameNotFoundException("User not found with username: " + username));

        // 如果找到了用户，直接返回 User 对象
        // 因为我们的 User 类已经实现了 Spring Security 的 UserDetails 接口
        return user;
    }
}